<template>
  <div class="addComponents">
    <a-modal
      v-if="addComponentVisible"
      @cancel="closeModel"
      :visible="addComponentVisible"
      :maskClosable="false"
      title="添加组件"
      :footer="null"
      :getContainer="getPopupContainer"
    >
      <a-form
        :model="addComponents"
        ref="addComponents"
        @finish="confirmAddSvg"
      >
        <a-form-item
          label="组件类型"
          name="createType"
          :rules="[{ required: true, message: '请选择组件类型!' }]"
        >
          <a-radio-group
            v-model:value="addComponents.createType"
            @change="changeRadio"
          >
            <a-radio
              v-for="item in panelOption"
              :key="item"
              :value="item.value"
            >
              {{ item.name }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="组件图标"
          name="priviewImg"
          :rules="[{ required: true, message: '请上传组件图标!' }]"
        >
          <a-upload
            v-model:file-list="fileList"
            :action="userUploader"
            list-type="picture-card"
            :maxCount="1"
            supportServerRender
            withCredentials
            :headers="{ token: token }"
            @preview="handlePreview"
            @change="uploadChange"
          >
            <div v-if="fileList.length < 1">
              <plus-outlined />
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
          label="组件标题"
          name="title"
          :rules="[{ required: true, message: '请输入组件标题!' }]"
        >
          <a-input
            v-model:value="addComponents.title"
            placeholder="请输入组件标题"
          />
        </a-form-item>
        <div class="button">
          <div>
            <a-form-item>
              <a-button type="default" @click="reset">重置</a-button>
            </a-form-item>
          </div>
          <div>
            <a-form-item>
              <a-button type="primary" html-type="submit">确定</a-button>
            </a-form-item>
          </div>
        </div>
      </a-form>
    </a-modal>
    <a-modal
      :visible="previewVisible"
      :title="addComponents.title"
      :footer="null"
      @cancel="handleCancel"
    >
      <img alt="example" style="width: 100%" :src="addComponents.priviewImg" />
    </a-modal>
  </div>
</template>
<script>
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { userUploader } from '@/network/api';
import { imageUrlToBase64 } from '@/util';
import Storage from '@/util/storage';
export default {
  props: ['addComponentVisible', 'getPopupContainer'],
  data() {
    return {
      fileList: [],
      userUploader: userUploader,
      token: '',
      previewVisible: false,
      labelCol: { span: 0 },
      wrapperCol: { span: 20 },
      panelOption: [
        {
          name: '背景图',
          value: 'bgImg',
        },
        {
          name: '贴图层',
          value: 'scatterLayer',
        },
      ],
      imageType: [
        {
          value: 'img',
        },
        { value: 'svg' },
      ],
      addComponents: {
        title: '', //标题
        //模板
        template: '',
        imgType: 'img',
        props: ['prop_data'], //数据接收
        //自定义属性
        defaultAttr: {},
        createType: 'scatterLayer', //创建类型
        priviewImg: '', //图片预览
      },
    };
  },
  components: {
    PlusOutlined,
  },
  created() {
    this.token = Storage.get('token');
  },
  methods: {
    confirmAddSvg() {
      this.$emit('confirmAddSvg', this.addComponents);
      this.reset();
    },
    closeModel() {
      this.reset();
      this.$emit('cancel', false);
    },
    reset() {
      this.$nextTick(() => {
        this.$refs['addComponents'].resetFields();
        this.fileList = [];
        this.addComponents.title = '';
      });
    },
    changeRadio(e) {
      let value = e.target.value;
      this.addComponents.createType = value;
      value == 'bgImg' ? (this.addComponents.imgType = 'img') : '';
    },
    inputTextarea(e) {
      let template = e.target.value;
      switch (this.addComponents.imgType) {
        case 'svg':
          this.regSvgAttribute(template, 'fill');
          this.regSvgAttribute(template, 'stroke');
          break;
        case 'img':
          break;
      }
    },
    /**查找svg可替换的改变的颜色
     * @param {*} template 模板字符
     * @param {*} str 匹配的字符
     */
    regSvgAttribute(template, str) {
      let reg = new RegExp(`${str}="#[a-zA-Z0-9]{3,6}`, 'g');
      let regArr = template.match(reg) ? template.match(reg) : '';
      regArr
        ? regArr.forEach((item, index) => {
            this.addComponents.template = this.addComponents.template.replace(
              item,
              `:${str}="prop_data.defaultAttr.${str}Color` +
                (index + 1) +
                '.val'
            );
            this.addComponents.defaultAttr[`${str}Color` + (index + 1)] = {
              title:
                str == 'fill' ? '填充色' + (index + 1) : '边框色' + (index + 1),
              val: item.match(/#[a-zA-Z0-9]{3,6}/g).toString(),
              type: 'colorinputbox',
            };
          })
        : '';
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
      }

      this.addComponents.priviewImg = file.url || file.preview;
      this.addComponents.title =
        file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
      this.previewVisible = true;
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    handleCancel() {
      this.previewVisible = false;
      this.addComponents = {
        title: '', //标题
        //模板
        template: '',
        imgType: 'img',
        props: ['prop_data'], //数据接收
        //自定义属性
        defaultAttr: {},
        createType: 'draggable', //创建类型
        priviewImg: '', //图片预览
      };
    },
    uploadChange(e) {
      if (e.file.status == 'done') {
        this.addComponents.priviewImg = e.file.response.filePath;
        imageUrlToBase64(e.file.response.filePath).then((base64URL) => {
          this.addComponents.template =
            this.addComponents.imgType == 'img'
              ? `<image x="-33" y="-33" width="66" height="66" xlink:href="${base64URL}" />`
              : '';
          this.addComponents.title = e.file.name;
        });
      } else if (e.file.status == 'error') {
        let error = e.file.response.error
          ? e.file.response.error
          : e.file.response.message;
        this.fileList = [];
        message.error(error + e.file.response.status);
        this.addComponents.priviewImg = '';
        this.addComponents.template = '';
        this.addComponents.title = '';
      }
      if (!e.fileList.length) {
        this.addComponents.title = '';
        this.fileList = [];
        this.addComponents.priviewImg = '';
      }
    },
  },
};
</script>
<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.button {
  display: flex;
}
.button > div {
  text-align: center;
  flex: 1;
}
.button .ant-row {
  display: inline !important;
  flex-flow: row wrap !important;
}
</style>
